package com.spic.system.service.impl;

import com.spic.common.core.constant.UserConstants;
import com.spic.common.core.exception.ServiceException;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.SpringUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.security.utils.cache.DeptCacheUtils;
import com.spic.common.security.utils.cache.PostCacheUtils;
import com.spic.common.security.utils.cache.UserCacheUtils;
import com.spic.system.api.domain.SysDept;
import com.spic.system.api.domain.SysRole;
import com.spic.system.api.domain.SysUser;
import com.spic.system.api.dto.DeptDTO;
import com.spic.system.api.dto.PostDTO;
import com.spic.system.api.dto.UserDTO;
import com.spic.system.domain.SysPost;
import com.spic.system.domain.SysUserPost;
import com.spic.system.domain.SysUserRole;
import com.spic.system.domain.UserExport;
import com.spic.system.enums.UserExportConstant;
import com.spic.system.mapper.*;
import com.spic.system.service.ISysConfigService;
import com.spic.system.service.ISysDeptService;
import com.spic.system.service.ISysPostService;
import com.spic.system.service.ISysUserService;
import com.spic.system.utils.CharacterConversionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingUserCache();
    }

    //加载用户缓存
    @Override
    public void loadingUserCache() {
        List<UserDTO> userDTOS = userMapper.listUsers();
        UserCacheUtils.setCache(userDTOS);
    }
    /**
     * 清空用户缓存数据
     */
    @Override
    public void clearUserCache()
    {
        UserCacheUtils.clearCache();
    }

    /**
     * 重置字用户缓存数据
     */
    public void resetUserCache()
    {
        clearUserCache();
        loadingUserCache();
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
//    @DataScope(deptAlias = "d", userAlias = "u",menuPath = "system/user/index")
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
//    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
//    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     *
     * 根据部门ids查询 部门主任
     * @param deptId
     * @return
     */
    @Override
    public List<SysUser> selectUserByZhuRenDeptId(Long[] deptId)
    {
        /**
         * 根据主部门查询 全部子部门  得到一个list集合
         */
        List<Long> listDeptIds = new ArrayList<>();
        for (int i=0;i<deptId.length;i++)
        {
            List<Long> longdeptIds = deptMapper.selectDeptAndChildrenIds(deptId[i]);
            listDeptIds.addAll(longdeptIds);
        }
        //将部门的集合 一个个取出来 赋值给新的数据
        Long [] temDeptId  = new Long[listDeptIds.size()];
        for (int i=0;i<listDeptIds.size();i++){
            temDeptId[i] = listDeptIds.get(i);
        }
        return userMapper.selectUserByZhuRenDeptId(temDeptId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }
    @Override
    public Map<String,Object> selectSysUserByUserIds(String userIds){
        Map<String,Object> map = new HashMap<>();
        String[] ids = userIds.split(",");
        long[] array = Arrays.asList(ids).stream().mapToLong(Long::parseLong).toArray();
        List<SysUser> sysUsers = userMapper.selectSysUserByUserIds(ArrayUtils.toObject(array));
        String nickNameIds = sysUsers.stream().map(SysUser::getNickName).collect(Collectors.joining(","));
        map.put("workGroup",nickNameIds);
        return map;
    }
    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        // 重置缓存
        resetUserCache();
        return rows;
    }

    /**
     * 导入时新增用户
     * @param user
     */
    public void insertUserExport(SysUser user){
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        boolean ret = userMapper.insertUser(user) > 0;
        resetUserCache();
        return ret;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        int rows = userMapper.updateUser(user);
        resetUserCache();
        return rows;
    }
    @Override
    public int updateUserCid(SysUser user)
    {
        SysUser sysUser = userMapper.selectUserByUserName(user.getUserName());
        user.setUserId(sysUser.getUserId());
        int rows = userMapper.updateUser(user);
        resetUserCache();
        return rows;
    }


    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
        resetUserCache();
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        int rows = userMapper.updateUser(user);
        resetUserCache();
        return rows;
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        int rows = userMapper.updateUser(user);
        resetUserCache();
        return rows;
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        int row = userMapper.updateUser(user);
        resetUserCache();
        return row;
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        int row = userMapper.resetUserPwd(userName, password);
        resetUserCache();
        return row;
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotNull(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        int row = userMapper.deleteUserById(userId);
        resetUserCache();
        return row;
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        int rows = userMapper.deleteUserByIds(userIds);
        resetUserCache();
        return rows;
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importUser(List<UserExport> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        Long deptId;
        Long postId;
        for (UserExport export : userList)
        {
            try
            {
                //必填字段验证
                if(StringUtils.isEmpty(export.getDeptName()) || StringUtils.isEmpty(export.getUserName()) ||
                        StringUtils.isEmpty(export.getPostName()) || StringUtils.isEmpty(export.getUserCode())) {
                    throw new ServiceException("<br/>人员编码/姓名/部门/岗位不能为空,请确认!");
                }
                //判断是否存在部门
                SysDept dept = sysDeptMapper.checkDeptNameUnique(export.getDeptName().trim(),
                        new Long(UserExportConstant.DEFAULT_DEPT.getCode()));
                //为空则新建部门
                if(StringUtils.isNull(dept)) {
                    deptId = this.createDept(operName, new Long(UserExportConstant.DEFAULT_DEPT.getCode()), export.getDeptName().trim());
                }else{
                    deptId = dept.getDeptId();
                }
                //不是机关和空则为班组,则判断班组
//                if(!UserExportConstant.JG_DEPT.getCode().equals(export.getClassGroup())
//                        && !UserExportConstant.NULL_DEPT.getCode().equals(export.getClassGroup())){
                    //判断是否存在班组
                    SysDept dept1 = sysDeptMapper.checkDeptNameUnique(export.getClassGroup().trim(), deptId);
                    if (StringUtils.isNull(dept1)) {//为空则新增班组，将deptId更改为班组id
                        deptId = this.createDept(operName, deptId, export.getClassGroup().trim());
                    }else{
                        deptId = dept1.getDeptId();
                    }
//                }
                //判断是否存在岗位
                SysPost post = postMapper.checkPostNameUnique(export.getPostName().trim());
                if(StringUtils.isNull(post)) {
                    postId = this.createPost(export.getPostName().trim(), operName);
                }else{
                    postId = post.getPostId();
                }
                //封装User对象
                SysUser user = this.buildUser(export, deptId, postId);
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(export.getUserCode().trim());
                if (StringUtils.isNull(u))
                {
                    user.setRoleIds(this.getRoleIds(export.getPostName().trim()));
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUserExport(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、人员编码 " + export.getUserCode() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setUserId(u.getUserId());
                    //判断是否存在此岗位，不存在则新增
                    List<Integer> postList = postMapper.selectPostListByUserId(u.getUserId());
                    if(!postList.contains(Integer.valueOf(String.valueOf(postId)))){
                        this.insertUserPost(user);
                    }
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、人员编码 " + export.getUserCode() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、人员编码 " + export.getUserCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、人员编码 " + export.getUserCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            resetCache();//重置缓存
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            resetUserCache();
        }
        return successMsg.toString();
    }

    /**
     * 重置部门、岗位、用户缓存
     */
    public void resetCache(){
        //部门
        DeptCacheUtils.clearCache();
        deptService.loadingDeptCache();
        //岗位
        PostCacheUtils.clearCache();
        postService.loadingPostCache();
        //用户
        UserCacheUtils.clearCache();
        this.loadingUserCache();
    }

    /**
     * 导入为空则新建部门
     * @param operName 创建人
     * @param pid 上级部门id
     * @param deptName 部门名称
     * @return deptId
     */
    public Long createDept(String operName, Long pid, String deptName){
        List<Map<String, Object>> list = sysDeptMapper.findListByPid(pid);
        SysDept dept = new SysDept();
        dept.setParentId(pid);
        dept.setDeptName(deptName);
        dept.setOrderNum(String.valueOf(list.size() + 1));
        dept.setCreateBy(operName);
        deptMapper.insertDept(dept);
        return dept.getDeptId();
    }

    /**
     * 导入为空则新增岗位
     * @param postName 岗位名称
     * @param operName 创建人
     * @return postId
     */
    public Long createPost(String postName, String operName){
        SysPost post = new SysPost();
        post.setPostName(postName);
        List<PostDTO> list = postMapper.listPosts();
        post.setPostSort(String.valueOf(list.size()+1));
        post.setStatus(UserExportConstant.STATUS_ZERO.getCode());
        post.setPostCode(CharacterConversionUtils.getStringAll(postName));
        post.setCreateBy(operName);
        postMapper.insertPost(post);
        return post.getPostId();
    }

    /**
     * 封装导入的User对象
     * @param export 导入数据
     * @param deptId 部门对象Id
     * @param postId 岗位对象Id
     * @return User对象
     */
    public SysUser buildUser(UserExport export, Long deptId, Long postId){
        SysUser user = new SysUser();
        user.setNickName(export.getUserName().trim());
        user.setPhonenumber(export.getPhoneNum().trim());
        if(UserExportConstant.SEX_MAN.getCode().equals(export.getSex().trim())){//男
            user.setSex(UserExportConstant.STATUS_ZERO.getCode());
        }else if(UserExportConstant.SEX_WOMAN.getCode().equals(export.getSex().trim())){//女
            user.setSex(UserExportConstant.STATUS_ONE.getCode());
        }else{
            user.setSex(UserExportConstant.STATUS_TWO.getCode());//未知
        }
        user.setUserName(export.getUserCode().trim());
        user.setDeptId(deptId);
        //设置岗位
        Long[] postIds = new Long[1];
        postIds[0] = postId;
        user.setPostIds(postIds);
        return user;
    }

    /**
     * 通过岗位获取角色
     * @param post
     * @return
     */
    public Long[] getRoleIds(String post){
        Long[] roleIds = new Long[1];
        String roleKey = "";
        if(post.contains(UserExportConstant.POST_ZR.getCode())
                && !post.contains(UserExportConstant.POST_FZR.getCode())){//主任岗位
            roleKey = UserExportConstant.ROLE_ZR.getCode();
        }else if(post.contains(UserExportConstant.POST_FZR.getCode())){//副主任岗位
            roleKey = UserExportConstant.ROLE_FZR.getCode();
        }else if(post.contains(UserExportConstant.POST_GZ.getCode())){//班组长岗位
            roleKey = UserExportConstant.ROLE_BZZ.getCode();
        }else if(post.contains(UserExportConstant.POST_DZ.getCode())){//班组长岗位
            roleKey = UserExportConstant.ROLE_BZZ.getCode();
        }else if(post.contains(UserExportConstant.POST_BZ.getCode())){//班组长岗位
            roleKey = UserExportConstant.ROLE_BZZ.getCode();
        }else{//普通角色
            roleKey = UserExportConstant.ROLE_PT.getCode();
        }
        SysRole role = roleMapper.checkRoleKeyUnique(roleKey);
        roleIds[0] = role.getRoleId();
        return roleIds;
    }


    @Override
    public List<Map<String, Object>> treeuser(long pid) {
        List<Map<String, Object>> list = sysDeptMapper.findListByPid(pid);

        List<Map<String, Object>> children;
        for (Map<String, Object>  m: list) {
            children = treeuser((long)m.get("id"));
            if (children != null && children.size() != 0) { //查询组织机构的子节点，并赋值给元素“children”
                m.put("children",children);
            } else {
                children = userMapper.findUserByOrgId((long)m.get("id")); //当根节点组织结构时，查询结构下面的员工，并赋值给根节点组织机构的children
                if (children != null && children.size() != 0) {
                    m.put("children",children);
                }
                //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
                if(children == null ||children.size() == 0){
                    m.put("disabled",true);
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> cascaderuser(long pid) {
        List<Map<String, Object>> list = sysDeptMapper.findListByPid1(pid);

        List<Map<String, Object>> children;
        for (Map<String, Object>  m: list) {
            children = cascaderuser((long)m.get("value"));
            if (children != null && children.size() != 0) { //查询组织机构的子节点，并赋值给元素“children”
                m.put("children",children);
            } else {
                children = userMapper.findUserByOrgId1((long)m.get("value")); //当根节点组织结构时，查询结构下面的员工，并赋值给根节点组织机构的children
                if (children != null && children.size() != 0) {
                    m.put("children",children);
                }
                //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
                if(children == null ||children.size() == 0){
                    m.put("disabled",true);
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> treeuserOfApp(long pid) {
        List<Map<String, Object>> list = sysDeptMapper.findListByPidOfApp(pid);

        List<Map<String, Object>> children;
        for (Map<String, Object>  m: list) {
            children = treeuserOfApp((long)m.get("value"));
            if (children != null && children.size() != 0) { //查询组织机构的子节点，并赋值给元素“children”
                m.put("children",children);
            } else {
                children = userMapper.findUserByOrgIdOfApp((long)m.get("value")); //当根节点组织结构时，查询结构下面的员工，并赋值给根节点组织机构的children
                if (children != null && children.size() != 0) {
                    m.put("children",children);
                }
                //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
                if(children == null ||children.size() == 0){
                    m.put("disabled",true);
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> treeuserOfApp2(long pid) {
        List<Map<String, Object>> list = sysDeptMapper.findListByPidOfApp2(pid);

        List<Map<String, Object>> children;
        for (Map<String, Object>  m: list) {
            children = treeuserOfApp2((long)m.get("id"));
            if (children != null && children.size() != 0) { //查询组织机构的子节点，并赋值给元素“children”
                m.put("children",children);
            } else {
                children = userMapper.findUserByOrgIdOfApp2((long)m.get("id")); //当根节点组织结构时，查询结构下面的员工，并赋值给根节点组织机构的children
                if (children != null && children.size() != 0) {
                    m.put("children",children);
                }
                //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
                if(children == null ||children.size() == 0){
                    m.put("disabled",true);
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> findUserByOrgId1(long deptId) {
        return  userMapper.findUserByOrgId1(deptId);
    }
    @Override
    public List<Map<String, Object>> findUserByOrgIdStr(long deptId) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> userByOrgId = userMapper.findUserByOrgId1(deptId);
        for (Map<String, Object> map : userByOrgId)
        {
            String value = (String) map.get("value");
            map.put("value",value);
            list.add(map);
        }
        return list;
    }

    @Override
    public SysUser selectWzUserIdByDeptId(String deptId) {
        return userMapper.selectWzUserIdByDeptId(deptId);
    }



    @Override
    public List<Map<String,Object>> getPostUser(){
        return userPostMapper.getPostUser();
    }

    @Override
    public SysUser selectUserInfoByUser(SysUser user){
        return userMapper.selectUserInfoByUser(user);
    }


    @Override
    public List<Map<String, Object>> treeuserDdUserByDeptId(long pid)
    {
        List<DeptDTO> deptDTOList = DeptCacheUtils.getCache();
         List<Long> aLong = new ArrayList<>();
        for (DeptDTO deptDTO : deptDTOList)
        {
            if(deptDTO.getParentId()==100L){
                aLong.add(deptDTO.getDeptId());
            }
        }
        //将部门的集合 一个个取出来 赋值给新的数据
        Long [] temDeptId  = new Long[aLong.size()];
        for (int i=0;i<aLong.size();i++){
            temDeptId[i] = aLong.get(i);
        }
        List<Map<String, Object>> list = sysDeptMapper.treeuserDdUserByDeptId(temDeptId,pid);
        List<Map<String, Object>> children;
        for (Map<String, Object>  m: list) {
            children = treeuserDdUserByDeptId((long)m.get("value"));
            if (children != null && children.size() != 0) { //查询组织机构的子节点，并赋值给元素“children”
                m.put("children",children);
            } else {
                children = userMapper.findUserByOrgIdOfDdUserBydeptId((long)m.get("value")); //当根节点组织结构时，查询结构下面的员工，并赋值给根节点组织机构的children
                if (children != null && children.size() != 0) {
                    m.put("children",children);
                }
                //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
                if(children == null ||children.size() == 0){
                    m.put("disabled",true);
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> announceRoleTree(long pid)
    {
        List<Map<String, Object>> list = sysDeptMapper.findListByPidOfApp2(pid);
        List<Map<String, Object>> children = new ArrayList<>();
        for (Map<String, Object>  m: list) {
            List<Map<String, Object>> listByPidOfApp2 = sysDeptMapper.findListByPidOfApp2((long)m.get("id"));
            for (Map<String, Object> map : listByPidOfApp2)
            {
                children = userMapper.selectAnnounceByDeptId((long)map.get("id"));
                if(children!=null && children.size()>0){
                    break;
                }
            }
            if (children != null && children.size() != 0) {
                m.put("children",children);
            }
            //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
            if(children == null  ||  children.size() == 0){
                m.put("disabled",true);
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> announceDeptTreeAuth(long pid)
    {
        Long deptId = Long.valueOf(SecurityUtils.getDeptId());
        SysDept sysDept = getDeptId(deptId);
        Long deptId1 = sysDept.getDeptId();
        /**
         * 根据主部门查询 全部子部门  得到一个list集合
         */
        List<Long> longdeptIds = deptMapper.selectDeptAndChildrenIds(deptId1);

        //将部门的集合 一个个取出来 赋值给新的数据
        Long [] temDeptId  = new Long[longdeptIds.size()];
        for (int i=0;i<longdeptIds.size();i++){
            temDeptId[i] = longdeptIds.get(i);
        }
        List<Map<String, Object>> list = sysDeptMapper.treeUserDeptId(temDeptId,pid);
        List<Map<String, Object>> children;
        for (Map<String, Object>  m: list) {
            children = announceDeptTreeAuth((long)m.get("id"));
            if (children != null && children.size() != 0) { //查询组织机构的子节点，并赋值给元素“children”
                m.put("children",children);
            } else {
                children = userMapper.findUserByOrgIdOfApp2((long)m.get("id")); //当根节点组织结构时，查询结构下面的员工，并赋值给根节点组织机构的children
                if (children != null && children.size() != 0) {
                    m.put("children",children);
                }
                //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
                if(children == null ||children.size() == 0){
                    m.put("disabled",true);
                }
            }
        }
        return list;

    }

    public SysDept getDeptId(Long deptId){
        SysDept sysDept = deptService.selectDeptById(deptId);
        if(sysDept!=null){
            Long parentId = sysDept.getParentId();
            if(parentId!=100L){
                sysDept =  getDeptId(parentId);
            }else{
                return sysDept;
            }
        }
        return sysDept;
    }

    /**
     * 根据role 和部门获取 两票三种人用户
     * @param map      roleKey:三种人角色key      deptId 当前部门id       wwFlag 是否取外委人员     true and false
     * @return   三种人 和 外委部门人员 集合
     */
    @Override
    public List<Map<String,Object>> getSysUserListByRoleAndDept(Map<String, Object> map)
    {
        String roleKey = map.get("roleKey")+"";
        String deptIdStr = map.get("deptId")+"";
        Object wwFlag = map.get("wwFlag");
        Long deptId =  Long.valueOf(deptIdStr) ;
        SysDept sysDept = getDeptId(deptId);
        Long deptParentId = sysDept.getDeptId();
        //获取外委人员部门
        List<Long>  deptIde = deptMapper.selectDeptListByDeptParentId(deptParentId);
        if(deptIde!=null && deptIde.size()>0 && wwFlag != null){
            Long wwDeptId = deptIde.get(0);
            List<Map<String,Object>> List = userMapper.selectSysUserListByRoleAndDept(roleKey,deptId,wwDeptId);
            return List;
        } else{
            List<Map<String,Object>> List = userMapper.selectSysUserListByRoleAndDept(roleKey,deptId,null);
            return List;
        }
    }

    @Override
    public Long [] getUserListByParentId(Long parentDeptId)
    {
        /**
         * 根据主部门查询 全部子部门  得到一个list集合
         */
        List<Long> longdeptIds = deptMapper.selectDeptAndChildrenIds(parentDeptId);
        //将部门的集合 一个个取出来 赋值给新的数据
        Long [] temDeptId  = new Long[longdeptIds.size()];
        for (int i=0;i<longdeptIds.size();i++){
            temDeptId[i] = longdeptIds.get(i);
        }
        return temDeptId;
    }

    @Override
    public List<SysUser> listUserByDepts(Long[] depts)
    {
        return userMapper.listUserByDepts(depts);
    }

    @Override
    public List<Map<String, Object>> selectAdminByRoleAndDept(Map<String, Object> map) {
        return userMapper.selectAdminByRoleAndDept(map);
    }
}
